package com.ruoyi.business.modbus.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.device.domain.Device;
import com.ruoyi.business.modbus.serial.ISerialPortService;
import com.ruoyi.business.modbus.domain.ModbusMasterDevice;
import com.ruoyi.business.modbus.domain.ModbusTcpMasterDevice;

import java.util.List;
import java.util.Map;

/**
 * 串口管理Controller
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/business/modbus/serialPort")
public class SerialPortController extends BaseController
{
    @Autowired
    private ISerialPortService serialPortService;

    /**
     * 测试串口连接
     */
    @PreAuthorize("@ss.hasPermi('business:serialport:test')")
    @Log(title = "测试串口连接", businessType = BusinessType.OTHER)
    @PostMapping("/testConnection")
    public AjaxResult testSerialPortConnection(@RequestBody Device device)
    {
        ModbusMasterDevice cfg = buildModbusMasterDevice(device);
        boolean result = serialPortService.testSerialPortConnection(cfg);
        return result ? success("串口连接成功") : error("串口连接失败");
    }

    /**
     * 测试串口连接 (兼容前端API调用)
     */
    @PreAuthorize("@ss.hasPermi('business:serialport:test')")
    @Log(title = "测试串口连接", businessType = BusinessType.OTHER)
    @PostMapping("/test")
    public AjaxResult testSerialPort(@RequestBody Device device)
    {
        ModbusMasterDevice cfg = buildModbusMasterDevice(device);
        boolean result = serialPortService.testSerialPortConnection(cfg);
        return result ? success("串口连接成功") : error("串口连接失败");
    }

    /** 将 Device 映射为 ModbusMasterDevice（当前仅支持TCP） */
    private ModbusMasterDevice buildModbusMasterDevice(Device device) {
        ModbusTcpMasterDevice cfg = new ModbusTcpMasterDevice();
        cfg.setDeviceSN(String.valueOf(device.getDeviceRelayCode()));
        cfg.setDeviceName(device.getDeviceName());
        cfg.setIpAddress(device.getIpAddress());
        cfg.setPort(device.getPort());
        return cfg;
    }

    /**
     * 获取可用串口列表
     */
    @PreAuthorize("@ss.hasPermi('business:serialport:query')")
    @GetMapping("/availablePorts")
    public AjaxResult getAvailableSerialPorts()
    {
        String[] ports = serialPortService.getAvailableSerialPorts();
        return success(ports);
    }

    /**
     * 获取可用串口列表 (兼容前端API调用)
     */
    @PreAuthorize("@ss.hasPermi('business:serialport:query')")
    @GetMapping("/available")
    public AjaxResult getAvailableSerialPortsForFrontend()
    {
        String[] ports = serialPortService.getAvailableSerialPorts();
        return success(ports);
    }

    /**
     * 检查串口是否可用
     */
    @PreAuthorize("@ss.hasPermi('business:serialport:query')")
    @GetMapping("/checkPort/{portName}")
    public AjaxResult checkSerialPort(@PathVariable("portName") String portName)
    {
        boolean available = serialPortService.isSerialPortAvailable(portName);
        return success(available);
    }

    /**
     * 获取当前使用的串口库名称
     */
    @PreAuthorize("@ss.hasPermi('business:serialport:query')")
    @GetMapping("/libraryName")
    public AjaxResult getSerialLibraryName()
    {
        String libraryName = serialPortService.getSerialLibraryName();
        return success(libraryName);
    }

    /**
     * 检查串口库是否可用
     */
    @PreAuthorize("@ss.hasPermi('business:serialport:query')")
    @GetMapping("/checkLibrary")
    public AjaxResult checkSerialLibrary()
    {
        boolean available = serialPortService.isSerialLibraryAvailable();
        return success(available);
    }

    /**
     * 获取串口服务信息
     */
    @PreAuthorize("@ss.hasPermi('business:serialport:query')")
    @GetMapping("/info")
    public AjaxResult getSerialPortInfo()
    {
        Map<String, Object> info = Map.of(
            "serviceType", "SerialPort Management",
            "description", "专门处理串口连接和管理功能",
            "features", List.of(
                "串口连接测试",
                "可用串口列表获取",
                "串口状态检查",
                "串口库信息查询",
                "串口库可用性检查"
            ),
            "libraryName", serialPortService.getSerialLibraryName(),
            "libraryAvailable", serialPortService.isSerialLibraryAvailable(),
            "availablePorts", serialPortService.getAvailableSerialPorts()
        );
        return success(info);
    }
}
